package com.atguigu.edu.realtime.app.dwd.traffic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.common.KafkaTopicConfig;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.KafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @ClassName: DwdTrafficUniqueVisitorDetail
 * @Description: TODO 流量域独立访客事务事实表
 * @Author: zhaoxunfeng
 * @Date: 2022-08-31 15:41
 * @Version: 1.0.0
 */
public class DwdTrafficUniqueVisitorDetail {
    public static void main(String[] args) {
        // TODO 1、获取一个执行入口环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(3);

        //TODO 2、消费kafka dwd_traffic_page_log主题的数据并创建流
        String groupId = "DwdTrafficUniqueVisitorDetail";
        DataStreamSource<String> kafkaDS = env.addSource(KafkaUtil.getKafkaConsumer(KafkaTopicConfig.DWD_TRAFFIC_PAGE_LOG_TOPIC, groupId));

        //TODO 3、过滤last_page_id不为Null的数据
        SingleOutputStreamOperator<JSONObject> filterDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject json = JSONObject.parseObject(value);
                if (json.getJSONObject("page").getString("last_page_id") == null) {
                    out.collect(json);
                }
            }
        });

        //TODO 4、按照mid进行分组
        KeyedStream<JSONObject, String> keyedStream = filterDS.keyBy(json -> json.getJSONObject("common").getString("mid"));

        //TODO 5、按照mid进行去重
        SingleOutputStreamOperator<JSONObject> processDS = keyedStream.process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {

            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("midState", String.class);
                // 设置状态有效时间为1天,如果超过有效时间就会被清除
                stateDescriptor.enableTimeToLive(StateTtlConfig
                        .newBuilder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build());
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public void processElement(JSONObject json,
                                       Context ctx,
                                       Collector<JSONObject> out) throws Exception {
                String logDate = DateFormatUtil.toDateString(json.getLong("ts"));
                String value = valueState.value();
                if (value == null) {
                    valueState.update(logDate);
                    out.collect(json);
                } else if (!value.equals(logDate)) {
                    out.collect(json);
                }
            }
        });

        //TODO 6、将得到的结果写入到Kafka 的主题中
        processDS.map(JSONObject::toString).print();
        processDS.map(JSONObject::toString).addSink(KafkaUtil.getKafkaProducer(KafkaTopicConfig.DWD_TRAFFIC_UNIQUE_VISITOR_DETAIL_TOPIC));

        //TODO 7、
        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
